package edu.ayit.controller.admin;

import edu.ayit.pojo.User;
import edu.ayit.service.UserService;
import edu.ayit.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserService userService;


    //跳转到登录页面
    @GetMapping
    public String loginPage(HttpSession session){
        return "admin/login";
    }

    //登录页面
    @PostMapping("/login")
    public String login(@RequestParam String username,
                 @RequestParam String password,
                 HttpSession session)
    {
        User user = userService.checkUser(username, MD5Utils.code(password));
        if (user != null) {
            session.setAttribute("user",user);
            return "admin/index";
        }
        session.setAttribute("msg","用户或密码错误！");
        return "redirect:/admin";
    }


    //注销登录
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
